package day1.HomeWork;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

/**
 * ClassName：TestServe
 *
 * @Author：小鱼
 * @Create：2025-08-25 15:25
 */
public class Test3Serve {
    /*
    (2)搭建TCP服务器，端口8002
     ①接收客户端发送的所有老师对象，遍历输出，并将老师信息全部写入本地文件 teacher.txt
     ②写入完成后，返回给客户端一个信息: "ok"
     ③关闭服务器
    */
    public static void main(String[] args) throws Exception{
        int port = 8002;
        ServerSocket serve = new ServerSocket(port);
        //如何等待
        Socket socket = serve.accept();
        System.out.println("服务端：与客户端连接成功： "+socket);
        //获取IO流，传输数据
        ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
        ObjectOutputStream os= new ObjectOutputStream(socket.getOutputStream());
        // 读取客户端发送的老师列表
        List<Teacher> teachers = (List<Teacher>) is.readObject();

        // 遍历并输出老师信息
        System.out.println("收到的老师信息如下：");
        for (Teacher teacher : teachers) {
            System.out.println(teacher);
        }

        // 将老师信息写入本地文件
        File file = new File("D:\\IDEA_project\\JP_Java\\week7\\src\\day1\\HomeWork\\teacher.txt");
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream fos2 = new ObjectOutputStream(fos);

        for (Teacher teacher : teachers) {
            fos2.writeObject(teacher.toString() + "\n");
        }
        System.out.println("老师信息已成功写入teacher.txt文件");

        // 向客户端发送"ok"确认信息
        os.writeObject("ok");
        os.flush();
        System.out.println("已向客户端发送确认信息");
        //关闭流
        fos2.close();
        fos.close();
        os.close();
        is.close();
        socket.close();
        serve.close();
    }
}